package org.ravenhearte.engine.helpers;

import org.ravenhearte.engine.input.EventHandler;
import org.ravenhearte.engine.input.InputEvent;
import org.ravenhearte.engine.input.InputEventManager;
import org.ravenhearte.engine.input.InputEvent.EventType;
import org.ravenhearte.engine.input.InputEventManager.Queue;

import com.jme.intersection.BoundingPickResults;
import com.jme.intersection.PickResults;
import com.jme.math.Ray;
import com.jme.math.Vector3f;
import com.jme.scene.Geometry;
import com.jme.scene.Node;

public class GUIEventGenerator implements EventHandler {
	Node node;
	
	public GUIEventGenerator(Node node) {
		this.node = node;
		
		loadEvents();
	}

	@Override
	public boolean onEvent(InputEvent ev) {
		switch (ev.type) {
		case BUTTONDOWN:
			Vector3f screenPos = new Vector3f(ev.x, ev.y, 0);
			Vector3f endPoint = new Vector3f(ev.x, ev.y, 1);
			Vector3f direction = endPoint.subtract(screenPos).normalize();

			Ray ray = new Ray(screenPos, direction);

			PickResults results = new BoundingPickResults();
			results.clear();
			node.findPick(ray, results);

			if (results.getNumber() != 0) {
				Geometry closest = results.getPickData(0).getTargetMesh();

				for (int i = 1; i < results.getNumber(); i++) {
					Geometry picked = results.getPickData(i).getTargetMesh();

					if (picked.getZOrder() < closest.getZOrder()) {
						closest = picked;
					}
				}

				InputEvent evnt = new InputEvent();
				evnt.parent = this;
				evnt.type = EventType.CUSTOM;
				evnt.textId = "MousePress " + closest.getName();
				System.out.println(evnt.textId);
				System.out.println(evnt.textId);
				evnt.id = ev.id;
				evnt.x = ev.x;
				evnt.y = ev.y;
				InputEventManager.eM.generateEvent(evnt);
				return true;
			}
			break;
		case MOVE:
			break;
		case WHEEL:
			break;
		}
		
		return false;
	}
	
	private void loadEvents() {
		InputEvent evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.MOVE;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);

		evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.BUTTONDOWN;
		evnt.id = 0;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);

		evnt = new InputEvent();
		evnt.parent = this;
		evnt.type = EventType.BUTTONDOWN;
		evnt.id = 1;
		InputEventManager.eM.registerEvent(Queue.GUI, evnt);
	}

	@Override
	public void unloadEvents() {
		InputEventManager.eM.unregisterEvents(this);
	}
}
